from datetime import datetime
from app import db

class SystemInfo(db.Model):
    """系统基本信息模型"""
    __tablename__ = 'system_info'
    
    id = db.Column(db.Integer, primary_key=True)
    hostname = db.Column(db.String(64), nullable=False)
    os = db.Column(db.String(128), nullable=False)
    kernel = db.Column(db.String(64), nullable=False)
    arch = db.Column(db.String(32), nullable=False)
    machine = db.Column(db.String(64))
    version = db.Column(db.String(32))
    updated_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    @staticmethod
    def update_or_create(info_dict):
        """更新或创建系统信息记录"""
        # 过滤掉模型中不存在的字段
        valid_keys = {c.name for c in SystemInfo.__table__.columns}
        filtered_info = {k: v for k, v in info_dict.items() if k in valid_keys}

        info = SystemInfo.query.first()
        if info is None:
            info = SystemInfo(**filtered_info)
            db.session.add(info)
        else:
            # 更新属性
            for key, value in filtered_info.items():
                if hasattr(info, key):
                    setattr(info, key, value)
            info.updated_at = datetime.utcnow()
        
        db.session.commit()
        return info


class SystemStatus(db.Model):
    """系统状态记录模型"""
    __tablename__ = 'system_status'
    
    id = db.Column(db.Integer, primary_key=True)
    cpu_percent = db.Column(db.Float, nullable=False)
    memory_percent = db.Column(db.Float, nullable=False)
    memory_used = db.Column(db.BigInteger, nullable=False)  # 字节
    memory_total = db.Column(db.BigInteger, nullable=False)  # 字节
    disk_percent = db.Column(db.Float, nullable=False)
    disk_used = db.Column(db.BigInteger, nullable=False)  # 字节
    disk_total = db.Column(db.BigInteger, nullable=False)  # 字节
    temperature = db.Column(db.Float)  # 可能为空
    load_avg_1 = db.Column(db.Float)
    load_avg_5 = db.Column(db.Float)
    load_avg_15 = db.Column(db.Float)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    
    @staticmethod
    def create(status_dict):
        """创建系统状态记录"""
        # 添加3个负载值
        if 'loadavg' in status_dict and len(status_dict['loadavg']) >= 3:
            status_dict['load_avg_1'] = status_dict['loadavg'][0]
            status_dict['load_avg_5'] = status_dict['loadavg'][1]
            status_dict['load_avg_15'] = status_dict['loadavg'][2]
            del status_dict['loadavg']
            
        status = SystemStatus(**status_dict)
        db.session.add(status)
        
        # 如果记录超过1000条，删除最旧的记录
        count = SystemStatus.query.count()
        if count > 1000:
            oldest = SystemStatus.query.order_by(SystemStatus.timestamp).limit(count - 1000).all()
            for record in oldest:
                db.session.delete(record)
        
        db.session.commit()
        return status
    
    @staticmethod
    def get_latest():
        """获取最新的系统状态记录"""
        return SystemStatus.query.order_by(SystemStatus.timestamp.desc()).first()
    
    @staticmethod
    def get_history(hours=24):
        """获取历史记录"""
        since = datetime.utcnow() - datetime.timedelta(hours=hours)
        return SystemStatus.query.filter(SystemStatus.timestamp >= since)\
            .order_by(SystemStatus.timestamp).all()


class SystemLog(db.Model):
    """系统日志记录模型"""
    __tablename__ = 'system_logs'
    
    id = db.Column(db.Integer, primary_key=True)
    level = db.Column(db.String(16), nullable=False)  # INFO, WARNING, ERROR
    source = db.Column(db.String(64), nullable=False)  # 日志来源
    message = db.Column(db.Text, nullable=False)  # 日志内容
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    
    @staticmethod
    def log(level, source, message):
        """记录日志"""
        log = SystemLog(level=level, source=source, message=message)
        db.session.add(log)
        
        # 如果日志数量超过10000，删除最旧的日志
        count = SystemLog.query.count()
        if count > 10000:
            oldest = SystemLog.query.order_by(SystemLog.timestamp).limit(count - 10000).all()
            for record in oldest:
                db.session.delete(record)
        
        db.session.commit()
        return log 